;(function(){

    //==================== 平台 ===========================
    var isAndroid = false;
    var isIOS = false;

    var ua = navigator.userAgent.toLowerCase();
    if(ua.indexOf("iphone") >= 0){
        isIOS = true;
    }
    if(ua.indexOf("android") >= 0){
        isAndroid = true;
    }

    //==================== 事件 ===========================

    //事件常量
    var EVENTS = {
        "READY_EVENT" : "YzJSBridgeReady", //YzJSBridge对象准备就绪事件
        "BACK_EVENT" : "back",   //物理返回键回退事件
        "RESUME_EVENT" : "resume", //后台切换前台恢复事件
        "NEW_ORDER_EVENT" : "newOrder" //后台切换前台恢复事件
    };

    //触发事件（方便app触发事件）
    function trigger(eventName){
        var eventObj = document.createEvent('Events');
        eventObj.initEvent(eventName);
        document.dispatchEvent(eventObj);
    }

    //==================== 接口 ===========================

    //YzJSBridge是否准备就绪
    var isJsBridgeReady = false;

    //监听ready事件
    document.addEventListener(EVENTS.READY_EVENT,function(e){
        isJsBridgeReady = true;
    },false);

    //native接口常量
    var APIS = {
        "OPEN_APP": 'openApp', // 打开app
        "CHECK_API" : "checkApi", //检测接口
        "GET_USER_INFO" : "getUserInfo",    //获取登录用户信息
        "SEND_HTTP_REQUEST" : "sendHttpRequest",  //发送http请求
        "SELECT_PICTURE" : "selectPicture", //选择图片
        "TAKE_PICTURE" : "takePicture", //拍照
        "VIEW_PICTURE" : "viewPicture",  //预览图片
        "UPLOAD_PICTURE" : "uploadPicture", //上传图片
        "LOGOUT" : "logout",//退出登录
        "EXIT_APP":"exitApp", //退出app
        "DIAL" : "dial", //拨打电话
        "LOGIN" : "login", //跳转登录界面
        "SET_TITLE":"setTitle",//设置title
        "SHOW_OPTION_MENU":'showOptionMenu',//显示右上角操作按钮
        "HIDE_OPTION_MENU":'hideOptionMenu',//隐藏右上角操作按钮
        "SET_OPTION_MENU":'setOptionMenu',//设置右上角操作按钮与SHOW_OPTION_MENU配合使用
        "PUSH_WINDOW":'pushWindow',//新窗口打开
        "POP_WINDOW":'popWindow',//关闭当前窗口
        "POP_TO":"popTo",//返回首页
        "SET_BACK_OPTION":"setBackOption",//设置back键控制方式
        "TEST_VOICE_BROADCAST":"testVoiceBroadcast",//试听语音播报
        "SCAN":"scan",//扫码
        "SAVE_PICTURE":"savePicture",//保存图片到本地
        "OPEN_AUTHV2":"authV2",//首页授权获取支付宝uid
        "GET_APP_VERSION":"getAppVersion",//获取当前app的版本号
        "UPGRADE_APP":"upgradeApp",//更新app
    };

    //检测jsbridge
    function loopCheckJsBirdge(callback){
        if(isJsBridgeReady){
            callback();
        }else{
            var intervalObj = null;
            intervalObj = window.setInterval(function(){
            if(isJsBridgeReady){
                window.clearInterval(intervalObj);
                callback();
            }},100);
        }
    }

    //调用native接口
    //具体方法签名以及返回值，请前往RAP平台（http://10.200.41.131/workspace/myWorkspace.do?projectId=42#127）
    function call(apiName,data,callback){

        //处理缺省值
        if(!data){
            data = {};
        }else{
            if(typeof data == "function"){
                callback = data;
                data = {};
            }else if(data.toString() != "[object Object]"){
                DialogUtil.dialogWarn("AppUtil.call:参数必须为json对象");
                return;
            }
        }
        if(!callback){
            callback = function(){};
        }else{
            if(typeof callback != "function"){
                DialogUtil.dialogWarn("AppUtil.call:回调必须为函数");
                return;
            }
        }
        if(isZHKIOS||/cross-bm/i.test(navigator.userAgent)){
            loopCheckJsBirdge(function(){//检测jsbridge对象

                window.YzJSBridge.call(APIS.CHECK_API,{"apiName" : apiName},function(checkResult){//检测接口是否实现
                    var checkResultJSON = JSON.parse(checkResult);
                    if(checkResultJSON.success.toString() == "true"){

                        window.YzJSBridge.call(apiName,data,function(result){//解析返回数据为json
                            callback(JSON.parse(result));
                        });

                    }else{//接口未实现
                        // if("pushWindow" == apiName){
                        //     DialogUtil.dialogWarn("发现新版本，请安装最新版本");
                        // }else{
                        //     DialogUtil.dialogWarn("app接口【"+apiName+"】未实现");

                        // }
                        DialogUtil.dialogWarn("当前版本暂不支持使用该功能，请下载最新版本");
                    }
                })
            });
        }else{
            switch (apiName) {
                case window.AppUtil.APIS.PUSH_WINDOW:
                    window.location.href = '..'+data.url+'?'+App.urlParam;
                    break;
                case window.AppUtil.APIS.SEND_HTTP_REQUEST:
                debugger
                $.ajax({
                    "data":data.data,
            	    "type":"POST",
                    "url" : data.url,
                    "headers" : {
                        "sessionId" : App.sessionId,
                    },
                    "async" : false,
                    "contentType" : 'application/json;charset=utf-8',
                    "dataType" : "json",
                    "success" : function(result) {
                        callback(result);
                    },
                    "error" : function() {

                    }});
                    break;
                default:
                    break;
            }
        }
    }

    //暴露到全局
    window.AppUtil = {};
    window.AppUtil.device = {"isAndroid" : isAndroid , "isIOS" : isIOS};

    window.AppUtil.EVENTS = EVENTS;
    window.AppUtil.trigger = trigger;

    window.AppUtil.APIS = APIS;
    window.AppUtil.call = call;

})();
